package com.plat.net.udp;

import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.DatagramPacket;
import io.netty.util.CharsetUtil;


/**
 * 数据交换处理器
 */
public class UDPDataSwapHandler extends SimpleChannelInboundHandler<DatagramPacket> {

    private Channel channel;

    public UDPDataSwapHandler(Channel channel) {
        this.channel = channel;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket packet) {
        // 向客户端发送消息
        ByteBuf readBuffer = packet.content();
        Channel channel = ctx.channel();
        try {
            System.out.println("get data: " + readBuffer.toString(CharsetUtil.UTF_8));
            ctx.channel().writeAndFlush(new DatagramPacket(readBuffer, packet.sender()));
        } finally {
            readBuffer.release();
            channel.close();
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {

    }
}
